﻿using Assets.Scripts.Bvh.Common;
using System.Collections.Generic;
using UnityEngine;

namespace Assets.Scripts.Bvh.Cpu
{
    public class MeshLoader
    {
        // 对于具有MeshFilter组件的多个游戏对象
        public static List<Triangle> LoadTriangles(MeshFilter[] meshFilters, out AABB sceneAABB)
        {
            if (meshFilters.Length == 0)
            {
                sceneAABB = AABB.Invalid;
                return null;
            }

            sceneAABB = AABB.Invalid;
            var list = new List<Triangle>();
            Triangle tri = Triangle.Invalid;
            foreach (MeshFilter mf in meshFilters)
            {
                Mesh mesh = mf.sharedMesh;
                if (mesh != null)
                {
                    var meshBound = mesh.bounds;
                    Matrix4x4 matrix = mf.transform.localToWorldMatrix;
                    var meshBoundWorldMin = matrix.MultiplyPoint(meshBound.min);
                    var meshBoundWorldMax = matrix.MultiplyPoint(meshBound.max);
                    sceneAABB = sceneAABB.Union(meshBoundWorldMin, meshBoundWorldMax);

                    // 获取Mesh的三角形索引数组
                    int[] triangles = mesh.triangles;
                    Vector3[] vertices = mesh.vertices;

                    for (int i = 0; i < triangles.Length; i += 3)
                    {
                        Vector3 v0 = vertices[triangles[i]];
                        Vector3 v1 = vertices[triangles[i + 1]];
                        Vector3 v2 = vertices[triangles[i + 2]];

                        tri.v0 = v0;
                        tri.v1 = v1;
                        tri.v2 = v2;

                        list.Add(tri);
                    }
                }
            }
            return list;
        }

        // 对于单个mesh
        public static List<Triangle> LoadTriangles(Mesh mesh, out Bounds meshBounds)
        {
            if (mesh == null)
            {
                meshBounds = default;
                return null;
            }

            meshBounds = mesh.bounds;

            var list = new List<Triangle>();

            var triangles = mesh.triangles;
            var vertices = mesh.vertices;

            var trianglesCount = triangles.Length / 3;

            for (int i = 0; i < trianglesCount; i++)
            {
                var v0 = vertices[triangles[0 + i * 3]];
                var v1 = vertices[triangles[1 + i * 3]];
                var v2 = vertices[triangles[2 + i * 3]];
                var triangle = new Triangle() { v0 = v0, v1 = v1, v2 = v2 };
                list.Add(triangle);
            }

            return list;
        }
    }
}
